package com.vancouver.knows.business.service.impl;

import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pangu.service.ActionException;
import com.vancouver.knows.business.bean.AccessInfo;
import com.vancouver.knows.business.bean.EndpointsInfo;
import com.vancouver.knows.business.bean.AccessInfo.ServiceInfo;

public class TokenHandler extends ACheckableJsonParser {

	private HashMap<String, String> map = new HashMap<String, String>();

	@Override
	public void parserJson(byte[] data) throws ActionException {
		try {
			String dataStr = new String(data, "utf-8");
			JSONObject result = JSON.parseObject(dataStr);
			parserContent(result);
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof ActionException) {
				throw (ActionException) e;

			} else {
				throw new ActionException(ActionException.OPERATE_ERROR, "数据解析异常");
			}
		}
	}

	@Override
	protected void parserContent(JSONObject content) throws Exception {
		String accessStr = content.getString("access");
		AccessInfo accessInfo = JSON.parseObject(accessStr, AccessInfo.class);
		if (accessInfo != null) {
			String tokenId = accessInfo.getToken().getId();
			map.put("tokenId", tokenId);
			List<ServiceInfo> serviceCatalog = accessInfo.getServiceCatalog();
			for (ServiceInfo serviceInfo : serviceCatalog) {
				if ("cloudFiles".equals(serviceInfo.getName())) {
					List<EndpointsInfo> endpoints = serviceInfo.getEndpoints();
					for (EndpointsInfo endpointsInfo : endpoints) {
						if ("ORD".equals(endpointsInfo.getRegion())) {
							map.put("cloudFiles", endpointsInfo.getPublicURL());
							break;
						}
					}

				} else if ("cloudFilesCDN".equals(serviceInfo.getName())) {
					List<EndpointsInfo> endpoints = serviceInfo.getEndpoints();
					for (EndpointsInfo endpointsInfo : endpoints) {
						if ("ORD".equals(endpointsInfo.getRegion())) {
							map.put("cloudFilesCDN", endpointsInfo.getPublicURL());
							break;
						}
					}
				}
			}
		}
	}

	public HashMap<String, String> getMap() {
		return map;
	}

}
